package com.leyou.user.web;

import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.local.UserContext;
import com.leyou.common.exceptions.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
@RequestMapping("info")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 判断信息是否存在
     * @param data      要校验的数据
     * @param type      数据的类型，1是用户名，2是手机号码
     * @return      查询结果，true 表示存在，false表示不存在
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> existDataType(
            @PathVariable("data")String data,@PathVariable("type")Integer type) {
        //查询返回
        return ResponseEntity.ok(userService.existDataType(data, type));
    }

    /**
     * 发送短信验证码
     * @param phone     手机号
     * @return      wu
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone")String phone) {
        //调用方法
        userService.sendCode(phone);
        //返回
        return ResponseEntity.noContent().build();
    }

    /**
     * 注册
     * @param user      用户信息
     * @param code      code
     * @return          无
     */
    @PostMapping
    public ResponseEntity<Void> registry(@Valid User user, BindingResult result, @RequestParam("code") String code) {
        //判断是否有错误信息
        if (result.hasErrors()) {
            //用流获取
            String error = result.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining("|"));
            //抛出
            throw new LyException(400, error);
        }
        //调用方法注册
        userService.registry(user, code);
        //返回
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据用户名和密码查询
     * @param username    用户名
     * @param password      密码
     * @return              查询到的用户对象
     */
    @GetMapping
    public ResponseEntity<UserDTO> queryUser(@RequestParam("username") String username, @RequestParam("password") String password) {
        //查询
        UserDTO userDTO = userService.queryUser(username, password);
        //返回
        return ResponseEntity.ok(userDTO);
    }

    @GetMapping("/me")
    public ResponseEntity<UserDetails> me() {
        //从threadLocal中获取userDetails数据
        UserDetails user = UserContext.getUser();
        //返回
        return ResponseEntity.ok(user);
    }
}
